//
//  AppDelegate.m
//  pacc
//
//  Created by 测试 on 2018/5/15.
//  Copyright © 2018年 测试. All rights reserved.
//

#import "AppDelegate.h"
#import "ZXTabBarController.h"
#import "loginViewController.h"
#import "AppDelegate.h"
// 极光推送

#import "JPUSHService.h"
#import <AdSupport/AdSupport.h>
#import "iflyMSC/IFlyMSC.h"

#ifdef NSFoundationVersionNumber_iOS_9_x_Max
#import <UserNotifications/UserNotifications.h> // 这里是iOS10需要用到的框架
#endif

static NSString * const JPUSHAPPKEY = @"f67788ce2fc96b568a76ab96"; // 极光appKey
static NSString * const channel = @"Publish channel"; // 固定的

//#ifdef DEBUG // 开发环境

static BOOL const isProduction = FALSE; // 极光FALSE为开发环境

//#else // 生产环境
//
//static BOOL const isProduction = TRUE; // 极光TRUE为生产环境
//
//#endif

@interface AppDelegate ()<JPUSHRegisterDelegate> // 最新版的sdk需要实现这个代理方法


@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // Override point for customization after application launch.
    self.window = [[UIWindow alloc]initWithFrame:[UIScreen mainScreen].bounds];
    UIViewController *myVC=[[UIViewController alloc] init];
    myVC.view.backgroundColor = [UIColor whiteColor];
    self.window.rootViewController=myVC;
    [self.window makeKeyAndVisible];
    NSString *initString = [[NSString alloc] initWithFormat:@"appid=%@",@"5b18d4e4"];
    [IFlySpeechUtility createUtility:initString];
    //注册退出监听
//    [self commonInitListenEvents];
    NSString * token = [[NSUserDefaults standardUserDefaults]valueForKey:@"token"];
    my_AppDelegate.token = token;
    [SVProgressHUD show];
    if (token) {
        [NetWorking startPOSTRequestWithUrl:@"usergetPermissions" parameters:@{@"token":my_AppDelegate.token} logMes:@"" show:NO success:^(NSDictionary *data) {
            NSString * status = [NSString stringWithFormat:@"%@",[data objectForKey:@"status"]];
            if ([status isEqualToString:@"200"]) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    NSArray * roleArr = [data objectForKey:@"data"];
                    my_AppDelegate.placeO = NO;
                    my_AppDelegate.urgeO = NO;
                    my_AppDelegate.transferO = NO;
                    my_AppDelegate.grabO = NO;
                    my_AppDelegate.writeR = NO;
                    my_AppDelegate.auditR = NO;
                    my_AppDelegate.login = NO;
                    for (NSString * str in roleArr) {
                        NSLog(@"权限 = %@ ",str);
                        if ([str isEqualToString:@"placeO"]) {
                            my_AppDelegate.placeO = YES;
                            if (roleArr.count == 3) {
                                [SVProgressHUD showErrorWithStatus:@"暂无权限,无法登陆"];
                                return ;
                            }
                        }if ([str isEqualToString:@"urgeO"]) {
                            my_AppDelegate.urgeO = YES;
                            
                        }if ([str isEqualToString:@"transferO"]) {
                            my_AppDelegate.transferO = YES;
                            
                        }if ([str isEqualToString:@"grabO"]) {
                            my_AppDelegate.grabO = YES;
                            
                        }if ([str isEqualToString:@"writeR"]) {
                            my_AppDelegate.writeR = YES;
                            
                        }if ([str isEqualToString:@"auditR"]) {
                            my_AppDelegate.auditR = YES;
                            
                        }if ([str isEqualToString:@"assignO"]) {
                            my_AppDelegate.assignO = YES;
                            
                        }if ([str isEqualToString:@"login"]) {
                            my_AppDelegate.login = YES;
                            
                        }
                    }
                });
            }
            dispatch_async(dispatch_get_main_queue(), ^{
                if ([status isEqualToString:@"200"]) {
                    [self quitLoginViewController];
                }else{
                    [self setupMainViewController];
                }
                [SVProgressHUD dismiss];
            });
        } failure:^(NSError *error) {
            dispatch_async(dispatch_get_main_queue(), ^{
                [self setupMainViewController];
                [SVProgressHUD dismiss];

            });
        }];
    }else{
        dispatch_async(dispatch_get_main_queue(), ^{
            [self setupMainViewController];
            [SVProgressHUD dismiss];

        });
    }
    // 注册apns通知
    if ([[UIDevice currentDevice].systemVersion floatValue] >= 10.0)   {
#ifdef NSFoundationVersionNumber_iOS_9_x_Max
        JPUSHRegisterEntity * entity = [[JPUSHRegisterEntity alloc] init];
        entity.types = UNAuthorizationOptionAlert|UNAuthorizationOptionBadge | UNAuthorizationOptionSound;
        [JPUSHService registerForRemoteNotificationConfig:entity delegate:self];
#endif
    }
    else if ([[UIDevice currentDevice].systemVersion floatValue] >= 8.0) // iOS8, iOS9
    {
        //可以添加自定义categories
        [JPUSHService registerForRemoteNotificationTypes:(UIUserNotificationTypeBadge | UIUserNotificationTypeSound | UIUserNotificationTypeAlert) categories:nil];
    }
    else // iOS7
    {
        //categories 必须为nil
        [JPUSHService registerForRemoteNotificationTypes:(UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeSound | UIRemoteNotificationTypeAlert) categories:nil];
    }
    /*
     *  launchingOption 启动参数.
     *  appKey 一个JPush 应用必须的,唯一的标识.
     *  channel 发布渠道. 可选.
     *  isProduction 是否生产环境. 如果为开发状态,设置为 NO; 如果为生产状态,应改为 YES.
     *  advertisingIdentifier 广告标识符（IDFA） 如果不需要使用IDFA，传nil.
     * 此接口必须在 App 启动时调用, 否则 JPush SDK 将无法正常工作.
     */
    // 广告标识符
    NSString *advertisingId = [[[ASIdentifierManager sharedManager] advertisingIdentifier] UUIDString];
    
    // 如不需要使用IDFA，advertisingIdentifier 可为nil
    // 注册极光推送
    [JPUSHService setupWithOption:launchOptions appKey:JPUSHAPPKEY channel:channel apsForProduction:isProduction advertisingIdentifier:advertisingId];
    
    //2.1.9版本新增获取registration id block接口。
    [JPUSHService registrationIDCompletionHandler:^(int resCode, NSString *registrationID) {
        if(resCode == 0)
        {
            // iOS10获取registrationID放到这里了, 可以存到缓存里, 用来标识用户单独发送推送
            NSLog(@"registrationID获取成功：%@",registrationID);
            my_AppDelegate.registrationId = registrationID;
            [[NSUserDefaults standardUserDefaults] setObject:registrationID forKey:@"registrationID"];
            [[NSUserDefaults standardUserDefaults] synchronize];
        }
        else
        {
            NSLog(@"registrationID获取失败，code：%d",resCode);
        }
    }];

//    [self launchScreen];
    if (!my_AppDelegate.userid) {
        my_AppDelegate.userid = @"sss";
    }

    return YES;
}

-(void)registRemote{
  
}

-(void)launchScreen{
    UIView *lunchView = [[NSBundle mainBundle ]loadNibNamed:@"LaunchScreen" owner:nil options:nil][0];
    lunchView.frame = CGRectMake(0, 0, self.window.screen.bounds.size.width, self.window.screen.bounds.size.height);
    [self.window addSubview:lunchView];
    UIImageView *imageV = [[UIImageView alloc] initWithFrame:CGRectMake(0, 50, 320, 300)];
    NSString *str = @"http://club.dayoo.com/club_data/upload_photo/rtys/2008/07/21/988/2473.gif"; [imageV sd_setImageWithURL:[NSURL URLWithString:str] placeholderImage:[UIImage imageNamed:@"default1.jpg"]];
    [lunchView addSubview:imageV];
    [self.window bringSubviewToFront:lunchView];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(4 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [lunchView removeFromSuperview];
    });
//    [NSTimer scheduledTimerWithTimeInterval:6 target:self selector:@selector(removeLun) userInfo:nil repeats:NO];
}
// 注册推送
// ---------------------------------------------------------------------------------
- (void)applicationWillResignActive:(UIApplication *)application {
}


- (void)applicationDidEnterBackground:(UIApplication *)application {
    [[UIApplication sharedApplication] setApplicationIconBadgeNumber:0];
}


- (void)applicationWillEnterForeground:(UIApplication *)application {
    [application setApplicationIconBadgeNumber:0];
    [application cancelAllLocalNotifications];
}


- (void)applicationDidBecomeActive:(UIApplication *)application {
}


- (void)applicationWillTerminate:(UIApplication *)application {
}

// ---------------------------------------------------------------------------------
#pragma mark - 注册推送回调获取 DeviceToken
#pragma mark -- 成功
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken
{
    // 注册成功
    // 极光: Required - 注册 DeviceToken
    [JPUSHService registerDeviceToken:deviceToken];
    NSLog(@"deviceToken=%@",deviceToken);
}

#pragma mark -- 失败
- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error
{
    // 注册失败
    NSLog(@"did Fail To Register For Remote Notifications With Error: %@", error);
}

// ---------------------------------------------------------------------------------

// 这部分是官方demo里面给的, 也没实现什么功能, 放着以备不时之需
#if __IPHONE_OS_VERSION_MAX_ALLOWED > __IPHONE_7_1
- (void)application:(UIApplication *)application didRegisterUserNotificationSettings:(UIUserNotificationSettings *)notificationSettings
{
    
}

// Called when your app has been activated by the user selecting an action from
// a local notification.
// A nil action identifier indicates the default action.
// You should call the completion handler as soon as you've finished handling
// the action.
- (void)application:(UIApplication *)application handleActionWithIdentifier:(NSString *)identifier forLocalNotification:(UILocalNotification *)notification completionHandler:(void (^)())completionHandler
{
    
}

// Called when your app has been activated by the user selecting an action from
// a remote notification.
// A nil action identifier indicates the default action.
// You should call the completion handler as soon as you've finished handling
// the action.
- (void)application:(UIApplication *)application handleActionWithIdentifier:(NSString *)identifier forRemoteNotification:(NSDictionary *)userInfo completionHandler:(void (^)())completionHandler
{
    
}
#endif

// ---------------------------------------------------------------------------------
- (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification
{
    [JPUSHService showLocalNotificationAtFront:notification identifierKey:nil];
}

// ---------------------------------------------------------------------------------

#pragma mark - iOS7: 收到推送消息调用
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {
    
    // iOS7之后调用这个
    [JPUSHService handleRemoteNotification:userInfo];
    NSLog(@"iOS7及以上系统，收到通知");
    
    if ([[UIDevice currentDevice].systemVersion floatValue] < 10.0 || application.applicationState > 0)
    {
        // 程序在前台或通过点击推送进来的会弹这个alert
        NSString *message = [NSString stringWithFormat:@"iOS7-8-9收到的推送%@", [userInfo[@"aps"] objectForKey:@"alert"]];
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:message delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil, nil];
//        [alert show];
    }
    completionHandler(UIBackgroundFetchResultNewData);
}

// ---------------------------------------------------------------------------------

#pragma mark - iOS10: 收到推送消息调用(iOS10是通过Delegate实现的回调)
#pragma mark- JPUSHRegisterDelegate
#ifdef NSFoundationVersionNumber_iOS_9_x_Max
// 当程序在前台时, 收到推送弹出的通知
- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(NSInteger))completionHandler {
    
    NSDictionary * userInfo = notification.request.content.userInfo;
    NSLog(@"iOS10程序在前台通过点击通知2: %@", userInfo);

    if([notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]])
    {
        [JPUSHService handleRemoteNotification:userInfo];
        NSString *message = [NSString stringWithFormat:@"will%@", [userInfo[@"aps"] objectForKey:@"alert"]];
        NSLog(@"iOS10程序在前台时收到的推送: %@", message);
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:message delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil, nil];
//        [alert show];
    }
    
    completionHandler(UNNotificationPresentationOptionBadge|UNNotificationPresentationOptionSound|UNNotificationPresentationOptionAlert); // 需要执行这个方法，选择是否提醒用户，有Badge、Sound、Alert三种类型可以设置
}


// 程序关闭后, 通过点击推送弹出的通知
- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)())completionHandler {
    
    NSDictionary * userInfo = response.notification.request.content.userInfo;
    NSLog(@"iOS10程序关闭后通过点击通知: %@", userInfo);

    if([response.notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]])
    {
        [JPUSHService handleRemoteNotification:userInfo];
        NSString *message = [NSString stringWithFormat:@"did%@", [userInfo[@"aps"] objectForKey:@"alert"]];
        NSLog(@"iOS10程序关闭后通过点击推送进入程序弹出的通知: %@", message);
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:message delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil, nil];
//        [alert show];
    }
    
    completionHandler();  // 系统要求执行这个方法
}
#endif


- (void)setupMainViewController {

    if (1) {
        [self setupLoginViewController];
    }else {
        [self quitLoginViewController];
    }
    }
//进入登录页面
- (void)setupLoginViewController
{
    [self.window.rootViewController dismissViewControllerAnimated:YES completion:nil];
    loginViewController *loginVc = [[loginViewController alloc] init];
    self.window.rootViewController = loginVc;
}
//进入主页面
- (void)quitLoginViewController
{
    [self.window.rootViewController dismissViewControllerAnimated:YES completion:nil];
    ZXTabBarController *tabController = [[ZXTabBarController alloc] init];
    self.window.rootViewController = tabController;
}


-(BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation{
    [[IFlySpeechUtility getUtility] handleOpenURL:url];
    return YES;
}

-(UIInterfaceOrientationMask)application:(UIApplication *)application supportedInterfaceOrientationsForWindow:(UIWindow *)window
{
    if (_isLandscape) {
        //        NSLog(@"横屏");
        return UIInterfaceOrientationMaskLandscape;
    }
    else
    {
        //        NSLog(@"竖屏");
        return UIInterfaceOrientationMaskPortrait;
    }
}



#pragma mark - Core Data stack

@synthesize persistentContainer = _persistentContainer;

- (NSPersistentContainer *)persistentContainer {
    // The persistent container for the application. This implementation creates and returns a container, having loaded the store for the application to it.
    @synchronized (self) {
        if (_persistentContainer == nil) {
            _persistentContainer = [[NSPersistentContainer alloc] initWithName:@"pacc"];
            [_persistentContainer loadPersistentStoresWithCompletionHandler:^(NSPersistentStoreDescription *storeDescription, NSError *error) {
                if (error != nil) {
                    // Replace this implementation with code to handle the error appropriately.
                    // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
                    
                    /*
                     Typical reasons for an error here include:
                     * The parent directory does not exist, cannot be created, or disallows writing.
                     * The persistent store is not accessible, due to permissions or data protection when the device is locked.
                     * The device is out of space.
                     * The store could not be migrated to the current model version.
                     Check the error message to determine what the actual problem was.
                    */
                    NSLog(@"Unresolved error %@, %@", error, error.userInfo);
                    abort();
                }
            }];
        }
    }
    
    return _persistentContainer;
}

#pragma mark - Core Data Saving support

- (void)saveContext {
    NSManagedObjectContext *context = self.persistentContainer.viewContext;
    NSError *error = nil;
    if ([context hasChanges] && ![context save:&error]) {
        // Replace this implementation with code to handle the error appropriately.
        // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
        NSLog(@"Unresolved error %@, %@", error, error.userInfo);
        abort();
    }
}

@end
